package edu.drexel.cs544.group11.server;

import java.net.ServerSocket;

import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;

import edu.drexel.cs544.group11.serverpersistence.ProductPersistence;

/**
 * SERVICE
 * 
 * CONCURRENT
 * 
 * The server launcher and thread that accepts incoming connections.
 * 
 * CS 544
 * 
 * @author Group 11:
 * @author Jason Setzer
 * @author Tam Thongsima
 * @author Kenny Oyefara
 * @author Chase Miller
 * 
 * @date Spring 2013
 * 
 */
public class StartServer {
    final static int port = 5943; // SERVICE
    
    /**
     * Launcher method.
     * 
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
	if (args.length > 1) {
	    String persistenceLocation = args[0];
	    ProductPersistence productPersistence = new ProductPersistence(persistenceLocation);
	    Server server = new Server(productPersistence);
	    
	    // First we need a SocketFactory that will create
	    // SSL server sockets.
	    System.setProperty("javax.net.ssl.keyStore", args[1]);
	    System.setProperty("javax.net.ssl.keyStorePassword", "cs544group11");
	    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
	    ServerSocket ss = ssf.createServerSocket(port);
	    
	    while (true) {
		try {
		    // CONCURRENT
		    ClientConnection connection = new ClientConnection(server, (SSLSocket) ss.accept());
		    server.init(connection);
		}
		catch (Throwable t) {
		    // Under no circumstances do we want the server to crash if a thread gets messed up.  Consider removign it from teh list of connections though.
		    t.printStackTrace();
		}
	    }
	}
	
	else {
	    System.out.println("Usage: please provide two arguments: 1) an absolute path to the persistence xml file and 2) an absolute path to the keystore file.");
	}
    }
}
